﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Website.Logger;
using System.Drawing;
using DAL;
using BOL;
using WebLib;
using System.Web.Script.Services;
using System.Web.Services;
using Libero.FusionCharts;
using UtilityExtensions;
namespace UILGestion.ObraAdmin.EstructuraCompras
{
    public partial class EstructuraCostoEditForm : PageBaseForm
    {
        public EstructuraCostoEditForm()
        {
            bol = new EstructuraCostoBL();
            lista = new ListValueBL();    
        }

        private EstructuraCostoBL bol;
        private ListValueBL lista;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                {
                    internalid.Value = (string)Request.QueryString["id"];
                    idObra.Value = (string)Request.QueryString["idObra"];
                    menuObraCtrl1.loadMenu(int.Parse(idObra.Value), Request.AppRelativeCurrentExecutionFilePath);
                    FormatForm();

                }
                catch (SqlException sqlex)
                {
                    WebServerSideSqlError.Log(sqlex);
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


                }
                catch (Exception ex)
                {
                    WebServerSideError.Log(ex);
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

                }

            }
        }
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //int i = 0;
        }
        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            //int i = 0;
        }
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //int i = 0;
        }

        private void ShowAllComboBox()
        {
            monedaDDL.DataTextField = "descripcion";
            monedaDDL.DataValueField = "idInternal";
            monedaDDL.DataSource = lista.GetMoneda();
            monedaDDL.DataBind();


            //------
            MonedaSeleccionDDL.DataValueField = "idInternal";
            MonedaSeleccionDDL.DataTextField = "Descripcion";
            MonedaSeleccionDDL.DataSource = new ListValueBL().GetMoneda();
            MonedaSeleccionDDL.DataBind();
        }

        protected void btnContinue_OnClick(object sender, EventArgs e)
        {
            
            try
            {
                if (((Button)sender).Text == anteriorButton.Text)
                {
                    EstructuraCosto ec = new EstructuraCosto();
                    
                    int anterior = ec.getidAnterior(DbUtil.Db, int.Parse(internalid.Value), int.Parse(idObra.Value));
                    Response.Redirect("EstructuraCostoEditForm.aspx?idObra=" + idObra.Value + "&id=" + anterior.ToString(), true);

                }


                if (((Button)sender).Text == siguienteButton.Text)
                {
                    EstructuraCosto ec = new EstructuraCosto();
                    
                    int siguiente = ec.getidSiguiente(DbUtil.Db, int.Parse(internalid.Value), int.Parse(idObra.Value));
                    Response.Redirect("EstructuraCostoEditForm.aspx?idObra=" + idObra.Value + "&id=" + siguiente.ToString(), true);

                }
                if (((Button)sender).Text == refreshButton.Text)
                {
                    Response.Redirect("EstructuraCostoEditForm.aspx?idObra=" + idObra.Value + "&id=" + internalid.Value.ToString(), true);                    

                }
                if (((Button)sender).Text == nuevaOCBTN.Text)
                {
                    Response.Redirect("../OrdenCompras/OrdenCompraEditForm.aspx?idObra=" + idObra.Value + "&idEC=" + internalid.Value.ToString(), true);                    

                }
                if (((Button)sender).Text == nuevaGOBTN.Text)
                {
                    Response.Redirect("../OrdenCompras/GastoObraEditForm.aspx?idObra=" + idObra.Value + "&idEC=" + internalid.Value.ToString(), true);                    

                }

                



            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }




        }
           private EstructuraCosto PopulateObjectInsert()
        {
            //(DD/MM/yyyy)
            System.IFormatProvider MiFp =
                new System.Globalization.CultureInfo("es-ES", false);



            EstructuraCosto entity = new EstructuraCosto();
            entity.idInternal = int.Parse(internalid.Value);

            entity.descripcion = presupuestoTextBox.Text;
            entity.usuarioMod = (int)Session["idEmpleado"];
            //entity.moneda = monedaDropDownList.Text;
            //entity.tipoCambio = Convert.ToDecimal(tipoCambioTextBox.Text);
            //entity.monto = Convert.ToDecimal(montoLabel.Text);
            //entity.idObra = Convert.ToInt32(idObra.Value);
            //int idpadre = 0;
            //  int.TryParse(idPadreTextBox.Text.ToString(),out   idpadre);
            return entity;
        }

        private void FormatForm()
        {
           
            
            idECJuntaECItemList.Value = Parametros.GenerarID().ToString();
            ShowAllComboBox();
            readEC();
            setEstadisticas();
            BindEstructuraCostoItems();

            
            tipoCambioOBRADOL.Value = DbUtil.Db.Obras.Single(p => p.idInternal == idObra.Value.ToInt()).tipoCambio.Value.ToString();
            tipoCambioLBL.Text = tipoCambioOBRADOL.Value;
            simbolOBRADOL.Value = DbUtil.Db.Monedas.Single(p => p.idInternal == 4).simbol;    //dol
            simbolMonedaBase.Value = DbUtil.Db.Monedas.Single(p => p.idInternal == 3).simbol;   //base
            
            BindDataRecursosConfigurados();
            BindDataComparativosItem();
            

            idRecursoList.Value = Parametros.GenerarID().ToString();
            idRecursoNewList.Text = Parametros.GenerarID().ToString();
              //--------
            idreUsoECItemList.Value = Parametros.GenerarID().ToString();
            idNewInsumosECItemList.Value = Parametros.GenerarID().ToString();


            
        }



        //private void setEstadistica(ref DataSet ds)
        //{
        //    view_EstructuraCostoItem partida = new view_EstructuraCostoItem();


        //    var w = (from a in ds.Tables[partida.GetType().Name].AsEnumerable()
        //             //where  a.Field<int>("idPresupuesto") == int.Parse(internalid.Text) & a.RowState != DataRowState.Deleted
        //             select a.Field<decimal>("monto")).Sum();


        //    //if (w.Count() > 0)
        //    //{
        //    montoLabel.Text = w.ToString();
        //    //}
        //    UpdatePanelTotales.Update();

        //}
        protected void SortingItem(object sender, GridViewSortEventArgs e)
        {
              string orden = e.SortExpression + " " + GetSortDirection(e.SortExpression);
            
            recursoGridView.DataSource =
               new EstructuraCostoBL().getEstructuraCostoItemNivel0(int.Parse(internalid.Value), orden);

            recursoGridView.DataBind();
            UpdatePartida.Update();
        }

     

        private void BindEstructuraCostoItems()
        {


            recursoGridView.DataSource =
                new EstructuraCostoBL().getEstructuraCostoItemNivel0(int.Parse(internalid.Value));

            recursoGridView.DataBind();
            UpdatePartida.Update();
            


        }
        private void readEC()
        {

            EstructuraCostoBL bol = new EstructuraCostoBL();
            EstructuraCostoInfo exp = bol.Load(int.Parse(internalid.Value));



            presupuestoTextBox.Text = exp.descripcion;
            // monedaLabel.Text = exp.moneda;
            idObra.Value = exp.idObra.ToString();

            ECPanel.Update();
        }
        //protected string dividirRecurso(object value)
        //{

        //    string script;

        //    //UpdateTimer = new Timer();
        //    //UpdateTimer.Interval = 5000;

        //    script = String.Format("<script languaje=\"javascript\">var opciones=(\"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=750,height=350\");" +
        //              "window.open(\"InsumoRecuAdicionListForm.aspx?id=" + internalid.Value + "&idRecurso=" + value.ToString() + "&accion=Insert&ds=" + idobjectdsLabel.Value.ToString() + "\",\"\",opciones,true);" +
        //              "</script>");

        //    return "javascript:abrir_ventana(" + value + ")";
        //    //ClientScript.RegisterStartupScript(this.GetType(), "Recursos", script);


        //}

        //protected void accionButton_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        if ((sender as Button).ID == "agregarButton")
        //        {

        //            //UpdateTimer = new Timer();
        //            //UpdateTimer.Interval = 5000;

        //            string script;
        //            script = String.Format("<script languaje=\"javascript\">var opciones=(\"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=950,height=350\");" +
        //                      "window.open(\"RecursoAdicionListForm.aspx?id="+internalid.Value+"&idObra=" + idObra.Value.ToString() + "&idds=" + idobjectdsLabel.Value + "\",\"\",opciones,true);" +
        //                      "</script>");



        //            ClientScript.RegisterStartupScript(this.GetType(), "Recursos", script);
        //        }
        //        if ((sender as Button).ID == "refreshRecuButton")
        //        {
        //            BindDataPartida();
        //            //UpdatePartida.Update();
        //        }

        //    }
        //    catch (SqlException sqlex)
        //    {
        //        WebServerSideSqlError.Log(sqlex);
        //        ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //             "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);

        //    }
        //    catch (Exception ex)
        //    {
        //        WebServerSideError.Log(ex);
        //        ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //             "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

        //    }








        //}

        protected void UpdateTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                //BindData();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);

            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }



        #region "item"

        protected void OnPaging(object sender, GridViewPageEventArgs e)
        {
            //BindData();
            //GridView1.PageIndex = e.NewPageIndex;
            //GridView1.DataBind();
        }

        protected void Deleteitem(object sender, EventArgs e)
        {
            try
            {
                ImageButton lnkRemove = (ImageButton)sender;
               // view_EstructuraCostoItem item = new view_EstructuraCostoItem();

                // se actualiza al DB 

                EstructuraCostoBL EcBL = new EstructuraCostoBL();
                EcBL.deleteEstructuraCostoItem(int.Parse(lnkRemove.CommandArgument.ToString()));

              

                //Session[idobjectdsLabel.Value.ToString()] = ds;
                BindEstructuraCostoItems();

                setEstadisticas();
                BindDataRecursosConfigurados();

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            try
            {
                recursoGridView.EditIndex = e.NewEditIndex;


                //GridViewRow row = GridView1.Rows[parent_index];

                //UpdateTimer.Enabled = false;              


                BindEstructuraCostoItems();

                setEstadisticas();
                BindDataRecursosConfigurados();
                //recursoGridView.FooterRow.Visible = false;

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
            }

        }


        protected void CancelEditItem(object sender, GridViewCancelEditEventArgs e)
        {
            recursoGridView.EditIndex = -1;
            BindEstructuraCostoItems();

        }
        //protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        //{
        //    try
        //    {
        //        string idInternal = e.Keys[0].ToString();
        //        //string idInternal = ((Label)recursoGridView.Rows[e.RowIndex].FindControl("idInternalEditLabel")).Text;

        //        string cantidadBase = ((TextBox)recursoGridView.Rows[e.RowIndex].FindControl("cantidadEditTextBox")).Text;
        //        //string precioBase = ((TextBox)recursoGridView.Rows[e.RowIndex].FindControl("precioEditTextBox")).Text;
        //        string totalBase = ((TextBox)recursoGridView.Rows[e.RowIndex].FindControl("totalEditTextBox")).Text;



        //        DataSet ds = (DataSet)Session[idobjectdsLabel.Value.ToString()];
        //        // delTemplateRepuestosList(ref ds);
        //        foreach (DataRow drw in ds.Tables[0].Rows)
        //        {
        //            if (!(drw.RowState == DataRowState.Deleted))
        //            {
        //                if (drw["idInternal"].ToString() == idInternal)
        //                {

        //                    drw["cantidad"] = cantidadBase;
        //                    //drw["precio"] = precioBase;
        //                    drw["total"] = totalBase;
        //                    break;
        //                }
        //            }
        //        }
        //        Session[idobjectdsLabel.Value.ToString()] = ds;

        //        recursoGridView.EditIndex = -1;

        //        BindDataPartida();

        //    }
        //    catch (SqlException sqlex)
        //    {
        //        WebServerSideSqlError.Log(sqlex);


        //    }
        //    catch (Exception ex)
        //    {
        //        WebServerSideError.Log(ex);
        //    }

        //}


        private void ediciongrilla(GridViewRowEventArgs e)
        {
            Label cantidad = (Label)e.Row.FindControl("cantidadBaseLabel");
            //Label precio = (Label)e.Row.FindControl("precioBaseLabel");
            Label total = (Label)e.Row.FindControl("totalBaseLabel");
            Label idRecursoLabel = (Label)e.Row.FindControl("idRecursoEditLabel");


            //Label cantidad = (Label)recursoGridView.Rows[e.Row.RowIndex].FindControl("cantidadBaseLabel");
            //Label precio = (Label)recursoGridView.Rows[e.Row.RowIndex].FindControl("precioBaseLabel");
            //Label total = (Label)recursoGridView.Rows[e.Row.RowIndex].FindControl("totalBaseLabel");

            string idRecurso = idRecursoLabel.Text;


            //string idRecurso = ((Label)recursoGridView.Rows[e.Row.RowIndex].FindControl("idRecursoLabel")).Text;



            dbGestionDataContext _db = new dbGestionDataContext(Parametros.strConnString);
            Recurso recurso = _db.Recursos.Single(p => p.idInternal == int.Parse(idRecurso));



            cantidad.Text = (recurso.cantidad - recurso.cantidadUso).Value.ToString();
            //precio.Text = recurso.precio.ToString();
            total.Text = (recurso.parcial - recurso.parcialUso).Value.ToString();
        }
        protected void recursoGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
        {

            //if (e.Row.RowState == (System.Web.UI.WebControls.DataControlRowState.Alternate | System.Web.UI.WebControls.DataControlRowState.Edit))
            //{
            //    ediciongrilla(e);
            // }


            //  if(e.Row.RowState == DataControlRowState.Edit )
            //  {
            //      ediciongrilla(e);
            //  }





            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //    GridView gv = (GridView)e.Row.FindControl("GridView2");
                //    List<view_ECInsumoItem> ListECnivel1 =
                //        (List<view_ECInsumoItem>)Session[idEcInsumonivel1Obj.Value];


                //    gv.DataSource = null;
                //   int vi = ((view_EstructuraCostoItem)(e.Row.DataItem)).idInternal;

                //   var q = from i in ListECnivel1
                //           where i.idPadre == vi
                //           select i;
                ImageButton partirRec = (ImageButton)e.Row.FindControl("partirRecursoLinkButton");
                ImageButton DividirRecursoLinkButton = (ImageButton)e.Row.FindControl("DividirRecursoLinkButton");
                ImageButton lnkRemove = (ImageButton)e.Row.FindControl("lnkRemove");


                ImageButton gv = (ImageButton)e.Row.FindControl("imgdiv");
                gv.Visible = false;

                //partirRec.Visible = false;
                //DividirRecursoLinkButton.Visible = false;
                //lnkRemove.Visible = false;


                bool vi = ((EstructuraCostoitemRecursoInfo)(e.Row.DataItem)).bitSel;
                int? idjuntopadre = ((EstructuraCostoitemRecursoInfo)(e.Row.DataItem)).idJuntoPadre;
                int? idAgrupadoDes = ((EstructuraCostoitemRecursoInfo)(e.Row.DataItem)).idAgrupadoDestino;

                decimal? cantidadUso = ((EstructuraCostoitemRecursoInfo)(e.Row.DataItem)).cantidadUso;



                if (!vi & !idjuntopadre.HasValue)
                {
                    //e.Row.BackColor = Color.FromName("#99CCFF");

                    gv.Visible = true;
                    partirRec.Visible = false;
                    lnkRemove.Visible = false;
                    DividirRecursoLinkButton.Visible = false;
                    e.Row.Cells[0].BackColor = Color.FromName("#99CCFF");
                }
                if (cantidadUso > 0)
                {
                    //e.Row.BackColor = Color.FromName("#99CCFF");

                    partirRec.Visible = false;
                    DividirRecursoLinkButton.Visible = false;
                    lnkRemove.Visible = false;

                }

                if (idjuntopadre.HasValue | idAgrupadoDes.HasValue)
                {
                    //e.Row.BackColor = Color.FromName("#99CCFF");

                    partirRec.Visible = false;
                    DividirRecursoLinkButton.Visible = false;
                    lnkRemove.Visible = false;

                }


            }
        }

        protected void recursoitemGridView_RowCreated(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    if ((view_EstructuraCostoItem)e.Row.DataItem != null)
            //    {
            //        var a = (view_EstructuraCostoItem)e.Row.DataItem;
            //        //para ambos casos 


            //        if (a.bitsel.Value)
            //        {

            //            e.Row.BackColor = Color.FromName("#99FFCC");
            //        }

            //    }
            //}
        }




        #endregion


        protected void leerPresupuestoButton_click(object sender, EventArgs e)
        {
            int idInternal = int.Parse(((LinkButton)sender).CommandArgument.ToString());
            Response.Redirect("~/ObraAdmin/Presupuesto/PresupuestoReadForm.aspx?idObra=" + idObra.Value + "&id=" + idInternal.ToString());



        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            List<RecursoListInfo> lista = RecursoSeleccionPanel1.ItemLista;
            
                EstructuraCostoBL ec = new EstructuraCostoBL();
            

           foreach (var row in lista)
               {
                  
                       ec.addECItemFromRecurso(int.Parse(internalid.Value),
                           row.idInternal);
                 
               }

           if (lista.Count > 0)
           {
               BindEstructuraCostoItems();
               BindDataRecursosConfigurados();
               setEstadisticas();
           }
           ModalFindPopupExtender.Hide();
        }

        //protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        //{
        //    if (e.Row.RowType == DataControlRowType.DataRow)
        //    {
        //        HyperLink HyperLink1 = (HyperLink)e.Row.FindControl("HyperLink1");
        //        HyperLink1.Attributes.Add("onclick", "ShowMyModalPopup('" + GridView1.DataKeys[e.Row.RowIndex].Value + "')");
        //    }
        //} 




     

        #region "item Insumos"


        //private void BindDataItem(GridView gv)
        //  {
        //     GridView gv = (GridView)e.Row.FindControl("GridView2");
        //        DataSet ds=(DataSet) Session[idobjectdsLabel.Value];

        //        view_ECInsumoItem ecItem = new view_ECInsumoItem();

        //      //  dbGestionDataContext _db = new dbGestionDataContext(Parametros.strConnString);


        //        //foreach (DataRow item in ds.Tables[ecItem.GetType().Name].Rows)
        //        //{
        //        //    if (item.RowState != DataRowState.Deleted)
        //        //    {
        //        //        if (item["idPadre"]==)
        //        //        {


        //        //            insumos.Add(
        //        //        }
        //        //    }
        //        //}

        //        string vi = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[0].ToString();

        //      var q=from i in ds.Tables[ecItem.GetType().Name].AsEnumerable().Where(p=>p.RowState!=DataRowState.Deleted).AsEnumerable()
        //            where i.Field<int>("idPadre") == int.Parse(vi)
        //           select  i;

        //      if (q.Count() > 0)
        //      {

        //          gv.DataSource = null;
        //          gv.DataSource = q.CopyToDataTable();
        //          gv.DataBind();
        //      }

        //  }
        protected void DeleteInstitem(object sender, EventArgs e)
        {
            try
            {
                ImageButton lnkRemove = (ImageButton)sender;


                EstructuraCostoBL EcBL = new EstructuraCostoBL();

                bool result =
                EcBL.deleteEstructuraCostoItem(int.Parse(lnkRemove.CommandArgument.ToString()));
                if (result)
                {
                    BindEstructuraCostoItems();

                    setEstadisticas();
                    BindDataRecursosConfigurados();
                }




            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        //protected void EditInsItem(object sender, GridViewEditEventArgs e)
        //{
        //    try
        //    {

        //        int indexRecurso = -1;
        //        //recursoGridView.DataBind();

        //        GridView gv = (GridView)sender;

        //        for (int i = 0; i < recursoGridView.Rows.Count; i++)
        //        {
        //            //GridView gv = (GridView)recursoGridView.Rows[i].FindControl("GridView2");
        //            //if (gv != null)
        //            //{
        //            //if (gv.Rows.Count == 0)
        //            //{
        //            //    continue;
        //            //}

        //            if (recursoGridView.DataKeys[i].Values[0].ToString() == (gv.DataKeys[0].Values[1].ToString()))
        //            {
        //                indexRecurso = i;
        //                gv.EditIndex = e.NewEditIndex;

        //                // int parent_index = e.NewEditIndex;



        //                DataSet ds = (DataSet)Session[idobjectdsLabel.Value];
        //                // //GridViewRow row = GridView1.Rows[parent_index];

        //                view_ECInsumoItem ecItem = new view_ECInsumoItem();




        //                var q = from a in ds.Tables[ecItem.GetType().Name].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted).AsEnumerable()
        //                        where a.Field<int>("idPadre") == int.Parse(recursoGridView.DataKeys[i].Values[0].ToString())
        //                        select a;

        //                if (q.Count() > 0)
        //                {

        //                    gv.DataSource = null;
        //                    gv.DataSource = q.CopyToDataTable();
        //                    gv.DataBind();
        //                    //sender.
        //                    //UpdateInsumo.
        //                }
        //                break;



        //            }
        //        }
        //    }

        //    catch (SqlException sqlex)
        //    {
        //        WebServerSideSqlError.Log(sqlex);
        //        ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //             "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);

        //    }
        //    catch (Exception ex)
        //    {
        //        WebServerSideError.Log(ex);
        //        ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //             "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

        //    }

        //}


        protected void CancelInsEditItem(object sender, GridViewCancelEditEventArgs e)
        {

            try
            {
                //GridView2
                //recursoGridView.EditIndex = -1;
                BindEstructuraCostoItems();
                setEstadisticas();
                BindDataRecursosConfigurados();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);

            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }


        //private void totalizar(DataSet ds)
        //{
        //    view_ECInsumoItem ECitem = new view_ECInsumoItem();
        //    view_EstructuraCostoItem estructuraCostoItem = new view_EstructuraCostoItem();

        //    foreach (DataRow item in ds.Tables[estructuraCostoItem.GetType().Name].Rows)
        //    {
        //        if (item.RowState != DataRowState.Deleted)
        //        {

        //            //total en cantidad
        //            decimal cantidadSub = (from i in ds.Tables[ECitem.GetType().Name].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted)
        //                                   where i.Field<int>("idPadre") == item.Field<int>("idInternal")
        //                                   select i).Sum(p => p.Field<decimal>("cantidad"));


        //            decimal totalSub = (from i in ds.Tables[ECitem.GetType().Name].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted)
        //                                where i.Field<int>("idPadre") == item.Field<int>("idInternal")
        //                                select i).Sum(p => p.Field<decimal>("total"));



        //            //Totales
        //            item["cantidadSub"] = cantidadSub;
        //            item["totalSub"] = totalSub;

        //        }


        //    }




        //}

        //protected void UpdateInsItem(object sender, GridViewUpdateEventArgs e)
        //{
        //    try
        //    {
        //       GridView  gv=(GridView)sender;
        //        view_ECInsumoItem ECitem= new view_ECInsumoItem();
        //        view_ComparativoItem estructuraCostoItem = new view_ComparativoItem();

        //        //string idInternal = e.Keys[0].ToString();
        //        //string idInternal = ((Label)recursoGridView.Rows[e.RowIndex].FindControl("idInternalEditLabel")).Text;

        //        string cantidad = ((TextBox)gv.Rows[e.RowIndex].FindControl("cantidadInsEditTextBox")).Text;

        //        string total = ((TextBox)gv.Rows[e.RowIndex].FindControl("totalInsEditTextBox")).Text;



        //        DataSet ds = (DataSet)Session[idobjectdsLabel.Value.ToString()];


        //        // delTemplateRepuestosList(ref ds);
        //        foreach (DataRow drw in ds.Tables[ECitem.GetType().Name].Rows)
        //        {
        //            if (!(drw.RowState == DataRowState.Deleted))
        //            {
        //                if (drw["idInternal"].ToString() == gv.DataKeys[e.RowIndex].Values[0].ToString())
        //                {

        //                    drw["cantidad"] = cantidad;

        //                    drw["total"] = total;
        //                    break;
        //                }
        //            }
        //        }

        //        totalizar(ds);

        //        Session[idobjectdsLabel.Value.ToString()] = ds;

        //        gv.EditIndex = -1;

        //        BindDataPartida();



        //        //BindDataInsumo();

        //    }
        //    catch (SqlException sqlex)
        //    {
        //        WebServerSideSqlError.Log(sqlex);

        //        ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //         "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


        //    }
        //    catch (Exception ex)
        //    {
        //        WebServerSideError.Log(ex);
        //        ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //             "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

        //    }

        //}

        //private void edicionInstgrilla(GridViewRowEventArgs e)
        //{

        //      Label cantidad = (Label)e.Row.FindControl("cantidadBaseInsLabel");
        //      Label precio = (Label)e.Row.FindControl("precioInsBaseLabel");
        //      Label total = (Label)e.Row.FindControl("totalInsBaseLabel");


        //      DataSet ds= (DataSet) Session[idobjectdsLabel.Value];
        //      view_EstructuraCostoItem item= new view_EstructuraCostoItem();

        //      //Label idRecursoLabel = (Label)e.Row.FindControl("idRecursoInsEditLabel");


        //      //Label cantidad = (Label)recursoGridView.Rows[e.Row.RowIndex].FindControl("cantidadBaseLabel");
        //      //Label precio = (Label)recursoGridView.Rows[e.Row.RowIndex].FindControl("precioBaseLabel");
        //      //Label total = (Label)recursoGridView.Rows[e.Row.RowIndex].FindControl("totalBaseLabel");

        //      //string idRecurso = idRecursoLabel.Text;


        //      //string idRecurso = ((Label)recursoGridView.Rows[e.Row.RowIndex].FindControl("idRecursoLabel")).Text;
        //      string idpadre = ((System.Data.DataRowView)(e.Row.DataItem)).Row["idPadre"].ToString();

        //      var q = from drw in ds.Tables[item.GetType().Name].AsEnumerable().Where(p => p.RowState != DataRowState.Deleted)
        //              where drw.Field<int>("idInternal") == int.Parse(idpadre)
        //                  select drw;


        //      DataRow dr=q.First();
        //      decimal cantidaddr=dr.Field<decimal>("cantidad");
        //      decimal cantidadUsodr = dr.Field<decimal>("cantidadUso");
        //      decimal preciodr = dr.Field<decimal>("precio");
        //      decimal totaldr = dr.Field<decimal>("total");
        //      decimal totalUsodr = dr.Field<decimal>("TotalUso");

       
        //      cantidad.Text = Math.Round((cantidaddr - cantidadUsodr),2).ToString();
        //      precio.Text = Math.Round(preciodr, 2).ToString();
        //      total.Text = Math.Round((totaldr - totalUsodr), 2).ToString();
        //}

        protected void GridView2_RowDataBound(Object sender, GridViewRowEventArgs e)
        {


            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                bool vi = ((EstructuraCostoitemNivelInfo)(e.Row.DataItem)).bitSel;


                if (!vi)
                {
                    //e.Row.BackColor = Color.FromName("#99CCFF");

                    GridView gv = (GridView)e.Row.FindControl("GridView3");
                    int idPadre = ((EstructuraCostoitemNivelInfo)(e.Row.DataItem)).idInternal;
                    gv.DataSource = new EstructuraCostoBL().getEstructuraCostoItemNivel2(idPadre);
                    gv.DataBind();

                    e.Row.Cells[0].BackColor = Color.FromName("#99CCFF");

                }
            }

            //if (e.Row.RowState == (System.Web.UI.WebControls.DataControlRowState.Alternate | System.Web.UI.WebControls.DataControlRowState.Edit))
            //{
            //    edicionInstgrilla(e);
            //}


            //if (e.Row.RowState == DataControlRowState.Edit)
            //{
            //    edicionInstgrilla(e);
            //}







            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    GridView gv = (GridView)e.Row.FindControl("GridView2");
            //    List<view_EstructuraCostoItem> ListECnivel1 =
            //        (List<view_EstructuraCostoItem>)Session[idEcInsumonivel1Obj.Value];


            //    gv.DataSource = null;
            //    string vi = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[0].ToString();

            //    var q = from i in ListECnivel1
            //            where i.idPadre == int.Parse(vi)
            //            select i;

            //    if (q.Count() > 0)
            //    {

            //        gv.DataSource = q;
            //        gv.DataBind();
            //    }
            //}
        }



        #endregion


        #region "Partir Recurso"
        protected void aceptarPartirButton_Click(object sender, EventArgs e)
        {

            try
            {

               
               
                PresupuestoBL presupuestoBL = new PresupuestoBL();
                EstructuraCostoBL ECBL = new EstructuraCostoBL();
                int idusuario = (int)Session["idEmpleado"];

                int result = presupuestoBL.partirRecurso( ECItemPartirPanel1.idestructuraCostoitem, 
                    ECItemPartirPanel1.ItemLista);
                if (result>0)
                {

                    dbGestionDataContext _db = new dbGestionDataContext(DbUtil.strConnString);
                    var q = from a in _db.Recursos
                            where a.idPadre == result
                            select a;

                    foreach (var recursohijo in q)
                    {
                        ECBL.addECItemFromRecurso(int.Parse(internalid.Value), recursohijo.idInternal);
                    }


                    //cerrar la ventana
                    BindEstructuraCostoItems();
                    BindDataRecursosConfigurados();
                    ModalPartirPopupExtender.Hide();
                }
            }
            catch (SqlException sqlex)
            {
                ModalPartirPopupExtender.Show();
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                ModalPartirPopupExtender.Show();
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void partirRecurso_Click(object sender, EventArgs e)
        {

            try
            {
                 ImageButton lnkRemove = (ImageButton)sender;
                int idInternal = int.Parse(lnkRemove.CommandArgument.ToString());

                ECItemPartirPanel1.LoadRecursoPartir(idInternal);
                ModalPartirPopupExtender.Show();
               
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        
        #endregion


        #region Dividir EstructuraCostoItem


        [WebMethod(), ScriptMethod()]
        public static string GetRecursoDisponible(String prefixText, String contextKey)
        {
            InsumoBL bol = new InsumoBL();
            return bol.getInsumoAll(prefixText, 30);


        }

       
        private static int idTipoInsumo;
        protected void dividirRecurso_Click(object sender, EventArgs e)
        {
           

            try
            {
                //id de estructura de costo item
                ImageButton lnkRemove = (ImageButton)sender;
                int id = int.Parse(lnkRemove.CommandArgument.ToString());

                ECItemDetallarPanel1.LoadRecursoPartir(id);

                ModalDividirPopupExtender.Show();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);
            }
           

        }

     


        protected void aceptarDividirButton_Click(object sender, EventArgs e)
        {

            try
            {

                List<EstructuraCostoitemsingleInfo> recursoList = ECItemDetallarPanel1.ItemLista;
                


                EstructuraCostoBL presupuestoBL = new EstructuraCostoBL();
               

                bool result = presupuestoBL.dividirECitem(ECItemDetallarPanel1.idestructuraCostoitem,
                    recursoList);
                if (result)
                {

                    
                    //cerrar la ventana
                    BindEstructuraCostoItems();
                    setEstadisticas();
                    BindDataRecursosConfigurados();
                    ModalDividirPopupExtender.Hide();
                }
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }
       

        #endregion

        #region  "comparativos"
        protected void BindDataComparativosItem()
        {
            //ComparativosRegistradoGridView.DataSource = 
            //    new ComparativoBL().getComparativoListXEC(int.Parse(internalid.Value));
            //ComparativosRegistradoGridView.DataBind();

        }

        protected void nuevoComp_Click(object sender, EventArgs e)
        {
            Response.Redirect("../Comparativos/ComparativoInsertForm.aspx?idObra=" + idObra.Value + "&idEC=" + internalid.Value);

        }

        #endregion

        #region "Recursos Configurados"

        protected void SortingconfiguradosItem(object sender, GridViewSortEventArgs e)
        {
            string orden = e.SortExpression + " " + GetSortDirection(e.SortExpression);

            recursoConfiguradoGridView.DataSource =
               new EstructuraCostoBL().getEstructuraCostoItemConfig(int.Parse(internalid.Value), orden);

            recursoConfiguradoGridView.DataBind();
            recursosConfiguradosUpdatePanel.Update();
        }

        private void BindDataRecursosConfigurados()
        {

            recursoConfiguradoGridView.DataSource =
                        new EstructuraCostoBL().getEstructuraCostoItemConfig(int.Parse(internalid.Value));
            recursoConfiguradoGridView.DataBind();
            recursosConfiguradosUpdatePanel.Update();

        }



        //    protected void actualizarecursoConf_click(object sender, EventArgs e)
        //    {

        //        try 
        //{

        //    if (((Button)sender).Text == recursoConfButton.Text)
        //    {
        //        DataBindRecursosConfigurados();

        //    }

        //}
        //        catch (SqlException sqlex)
        //        {
        //            WebServerSideSqlError.Log(sqlex);
        //            ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //             "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


        //        }
        //        catch (Exception ex)
        //        {
        //            WebServerSideError.Log(ex);
        //            ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //             "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

        //        }

        //    }
        #endregion


        #region "Juntar /DesJuntar recursos"

        protected void juntar_click(object sender, EventArgs e)
        {
            try
            {

                ImageButton button = (ImageButton)sender;

                // traemos todos los recursos configurados que pueden ser Juntados
                int idECitem = int.Parse(button.CommandArgument.ToString());
                ECItemJuntarPanel1.LoadRecurso(idECitem);
                juntarModalpopupextender.Show();
               



            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }

      
        protected void itemAgrupadoGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            try
            {



                if (e.Row.RowType == DataControlRowType.DataRow)
                {



                    EstructuraCostoItemConfInfo ecitemConfg = ((EstructuraCostoItemConfInfo)(e.Row.DataItem));

                    var q = new BOL.EstructuraCostoBL().getEstructuraCostoItemJuntosConfig(ecitemConfg.idInternal);

                    Panel pan = (Panel)e.Row.FindControl("cagrupadoPanel");
                    ImageButton lnkdesjuntar = (ImageButton)e.Row.FindControl("lnkdesjuntar");
                    ImageButton lnkJuntar = (ImageButton)e.Row.FindControl("lnkJuntar");
                    System.Web.UI.WebControls.Image EcItemRef = (System.Web.UI.WebControls.Image)e.Row.FindControl("ImageECItemRef");
                    //ImageButton lnkpartirRecurso = (ImageButton)e.Row.FindControl("lnkpartirRecurso");

                    pan.Visible = false;
                    lnkdesjuntar.Visible = false;
                    EcItemRef.Visible = false;
                    //lnkpartirRecurso.Visible = false;


                    if (ecitemConfg.ECItemRef!=null)
                    {
                        EcItemRef.Visible = true;
                    }

                    if (q.Count() > 0)
                    {

                        GridView gv = (GridView)e.Row.FindControl("JuntosGridView");

                        pan.Visible = true;
                        lnkdesjuntar.Visible = true;
                        lnkJuntar.Visible = false;
                        e.Row.Cells[0].BackColor = Color.FromName("#99CCFF");
                        gv.DataSource = q;
                        gv.DataBind();
                    }
                }


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }


        protected void desagrupar_click(object sender, EventArgs e)
        {
            try
            {
                ImageButton button = (ImageButton)sender;
                string idItem = button.CommandArgument.ToString();
                int UsuarioCre = (int)Session["idEmpleado"];

                BOL.EstructuraCostoBL bl = new EstructuraCostoBL();
                bl.desjuntarEstructuraCostoItem(int.Parse(idItem), UsuarioCre);

                BindEstructuraCostoItems();
                setEstadisticas();
                BindDataRecursosConfigurados();
                BindDataComparativosItem();

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }




        protected void recursoJuntar_Click(object sender, EventArgs e)
        {
            try
            {
                if (((Button)sender).Text == juntarRecursoButton.Text)
                {


                   
                     
                      var k = ECItemJuntarPanel1.ItemLista;
                      
                      EstructuraCostoBL bol = new EstructuraCostoBL();

                      bol.juntarEstructuraCostoItem(k);


                      juntarModalpopupextender.Hide();
                      //setEstadisticas();
                      BindDataRecursosConfigurados();
                      BindDataComparativosItem();

                   
                }
                if (((Button)sender).Text == delJuntarRecursoButton.Text)
                {
                    juntarModalpopupextender.Hide();
                }

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }




        #endregion


        #region "Agrupacion de Items de Estructura"




        private void resetEmpty()
        {
            if (itemAgrupadoGridView.Rows.Count == 0)
            {
                List<EstructuraCostoItemRecursoInfo> itemList0 = new List<EstructuraCostoItemRecursoInfo>();
                EstructuraCostoItemRecursoInfo itemcero = new EstructuraCostoItemRecursoInfo();
                itemcero.idInternal = 0;
                itemList0.Add(itemcero);
                itemAgrupadoGridView.DataSource = itemList0;
                itemAgrupadoGridView.DataBind();
                itemAgrupadoGridView.Rows[0].Visible = false;
            }

        }
        private void resetEmptyNuevo()
        {
            if (itemGridView.Rows.Count == 0)
            {
                List<EstructuraCostoitemsingleInfo> itemList0 = new List<EstructuraCostoitemsingleInfo>();
                EstructuraCostoitemsingleInfo itemcero = new EstructuraCostoitemsingleInfo();
                itemcero.idInternal = 0;
                itemList0.Add(itemcero);
                itemGridView.DataSource = itemList0;
                itemGridView.DataBind();
                itemGridView.Rows[0].Visible = false;
            }

        }
       
        private void setEstadisticas()
        {
            var obra = DbUtil.Db.Obras.Single(p => p.idInternal == int.Parse(idObra.Value));
            EstructuraCostoBL bol = new EstructuraCostoBL();
            EstructurCostoItemTotalInfo info = bol.GetEstructuraCostoItemTotales(obra, int.Parse(internalid.Value)
                                                                            );
            totalPresupuestoLabel.Text = info.estructuraCostoBaseSoles;
            totalPresupuestoDLLLabel.Text = info.estructuraCostoBaseDollar;
            estructuraCostoLabel.Text = info.estructuraCostoUsoSoles;
            estructuraCostoDLLLabel.Text = info.estructuraCostoUsoDollar;
            totalConfiguradoDLLLabel.Text = info.estructuraCostoDispDollar;
            totalConfiguradoLabel.Text = info.estructuraCostoDispSoles;

            totalesPanel.GroupingText = string.Format("Tipo de Cambio Obra: {0:N3}", obra.tipoCambio.Value);



            totalesUpdatePanel.Update();


        }

        #region "Agrupados"


        private void BindDataAgrupadoItem()
        {

            List<EstructuraCostoItemRecursoInfo> item =
                (List<EstructuraCostoItemRecursoInfo>)Session[idRecursoList.Value.ToString()];

            monedaDDL.Enabled = true;
            if (item.Count > 0)
            {
                monedaDDL.Enabled = false;
            }
            itemAgrupadoGridView.DataSource = item;
            itemAgrupadoGridView.DataBind();
            resetEmpty(); //necesario para add

            //itemAgrupadoGridView.FooterRow.Visible = true;
            itemAgrupadoUpdatePanel.Update();
            setEstadisticaAgrupado();

            //partirUpdatePanel.Update();
            
        }
        private void setEstadisticaAgrupado()
        {
            List<EstructuraCostoItemRecursoInfo> itemRE =
                (List<EstructuraCostoItemRecursoInfo>)Session[idRecursoList.Value.ToString()];
            List<EstructuraCostoitemsingleInfo> itemNew =
                (List<EstructuraCostoitemsingleInfo>)Session[idRecursoNewList.Text.ToString()];
            
            TotalRecursoLabel.Text=String.Format("{0} {1:N4}",simbolMoneda.Value,itemRE.Sum(p=>p.total));
            TotalDetalleLabel.Text=String.Format("{0} {1:N4}",simbolMoneda.Value,itemNew.Sum(p=>p.total));

            saldoLabel.Text = String.Format("{0} {1:N4}", simbolMoneda.Value, itemRE.Sum(p => p.total) - itemNew.Sum(p => p.total));
            totalesUpdatePanel.Update();
        }

        protected void DeleteAgrupadoItem(object sender, EventArgs e)
        {
            try
            {

                ImageButton lnkRemove = (ImageButton)sender;
                int idInternal = int.Parse(lnkRemove.CommandArgument.ToString());

                List<EstructuraCostoItemRecursoInfo> itemList =
                    (List<EstructuraCostoItemRecursoInfo>)Session[idRecursoList.Value.ToString()];

                EstructuraCostoItemRecursoInfo drw = itemList.Single(p => p.idInternal == idInternal);

                //eliminamos de la coleccion

                itemList.Remove(drw);
                Session[idRecursoList.Value.ToString()] = itemList;



                BindDataAgrupadoItem();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        #endregion
        #region "Nuevo Item"

        private void BindDataItem()
        {

            List<EstructuraCostoitemsingleInfo> item =
                (List<EstructuraCostoitemsingleInfo>)Session[idRecursoNewList.Text.ToString()];




            itemGridView.DataSource = item;
            itemGridView.DataBind();
            resetEmptyNuevo(); //necesario para add

            itemGridView.FooterRow.Visible = true;
            //
            newrecursoUpdatePanel.Update();

            setEstadisticaAgrupado();

            //partirUpdatePanel.Update();






        }

        protected void DeleteItem(object sender, EventArgs e)
        {
            try
            {

                ImageButton lnkRemove = (ImageButton)sender;
                int idInternal = int.Parse(lnkRemove.CommandArgument.ToString());

                List<EstructuraCostoitemsingleInfo> itemList =
                    (List<EstructuraCostoitemsingleInfo>)Session[idRecursoNewList.Text.ToString()];

                EstructuraCostoitemsingleInfo drw = itemList.Single(p => p.idInternal == idInternal);

                //eliminamos de la coleccion
                //verificamos que no pertenece  a un ordenCompra
                 itemList.Remove(drw);
               
                Session[idRecursoNewList.Text.ToString()] = itemList;
                BindDataItem();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }


        protected void EditNewItem(object sender, GridViewEditEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);

                gv.EditIndex = e.NewEditIndex;
                BindDataItem();
                gv.FooterRow.Visible = false;


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void CancelNewItem(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);
                gv.EditIndex = -1;
                BindDataItem();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }



        protected void AddItem(object sender, EventArgs e)
        {
            try
            {

                List<EstructuraCostoitemsingleInfo> itemlist =
                  (List<EstructuraCostoitemsingleInfo>)Session[idRecursoNewList.Text];

                List<EstructuraCostoItemRecursoInfo> itemAgrupadolist =
                  (List<EstructuraCostoItemRecursoInfo>)Session[idRecursoList.Value];



                string precioStr = ((TextBox)itemGridView.FooterRow.FindControl("precioInsertTextBox")).Text;
                string cantidad = ((TextBox)itemGridView.FooterRow.FindControl("cantidadDividirInsertTextBox")).Text;
                string codigo = ((TextBox)itemGridView.FooterRow.FindControl("codigoInsertTextBox")).Text;
                string totalStr = ((TextBox)itemGridView.FooterRow.FindControl("totalInsertTextBox")).Text;


                DAL.Insumo insumo = DbUtil.Db.Insumos.Single(p => p.codigo == codigo.Trim());

                if (insumo.InsumoUnidad.abreviacion.ToUpper() == "GLB")
                {
                    cantidad = "1";
                }



                var total = totalStr.ToDecimal().Value;
                    
                decimal precio = Math.Round(total / cantidad.ToDecimal().Value,4);
                var d = itemAgrupadolist.Sum(p => p.total);
                var s = itemlist.Sum(p => p.total);

                if ((total - (d - s))>1)
                {

                    string msg = String.Format("No se permite montos superiores a: {0} {1:N4} ",
                        simbolMoneda.Value, Math.Round(itemAgrupadolist.Sum(p => p.total) - itemlist.Sum(p => p.total), 4));

                    throw new Exception(msg);
                }


                EstructuraCostoitemsingleInfo item =
                    new EstructuraCostoitemsingleInfo(UtilityExtensions.Util.GenerarID(),
                        insumo.idInternal,
                        insumo.codigo,
                        insumo.descripcion,
                        insumo.InsumoUnidad.abreviacion,
                        precio,
                        decimal.Parse(cantidad),
                        total,
                        simbolMoneda.Value,
                        monedaDDL.SelectedValue.ToInt());


                itemlist.Add(item);
                Session[idRecursoNewList.Text.ToString()] = itemlist;
                BindDataItem();

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        #endregion


        private void SetRowSelected(GridViewRow r, bool isSelected)
        {

            CheckBox cbSelected = r.FindControl("chkEmployeesSelector") as CheckBox;
            if (null != cbSelected)
                cbSelected.Checked = isSelected;
        }
        protected void accionItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (((Button)sender).ID == "addRecursoButton")
                {

                    RecursoSeleccionPanel1.loadRecursoGrupo();
                    RecursoSeleccionPanel1.LoadRecurso();
                    ModalFindPopupExtender.Show();

                }


                if (((Button)sender).ID == "AgruparRecursoButton")
                {
                    
                    Session[idRecursoList.Value.ToString()] = new List<EstructuraCostoItemRecursoInfo>();
                    Session[idRecursoNewList.Text.ToString()] = new List<EstructuraCostoitemsingleInfo>();
                   
                    BindDataItem();
                    BindDataAgrupadoItem();
                    
                    AgrupadoTransModalpopupextenderadd.Show();

                }


                if (((Button)sender).ID == ReAgruparRecursoButton.ID)
                {
                    //-------------
                    Session[idreUsoECItemList.Value.ToString()] = new List<EstructuraCostoitemReUsoInfo>();
                    Session[idNewInsumosECItemList.Value.ToString()] = new List<EstructuraCostoitemsingleInfo>();
                    int idMoneda = int.Parse(MonedaSeleccionDDL.SelectedValue);
                    this.LoadListaDisponible();
                    this.LoadNuevoUso();
                    ReAgruparRecursoModalPPE.Show();

                }

                if (((Button)sender).ID == eliminarAgrupadoButton.ID)
                {

                    
                    //ECItemElimReAgrupadoPanel2.ListView.DataSource = 
                    //    new EstructuraCostoBL().GetAgrupadoList(1,int.Parse(internalid.Value));
                    //ECItemElimReAgrupadoPanel2.ListView.DataBind();
                   
                    ECItemElimReAgrupadoPanel2.DataBind();
                    delAgrupadoUpdatePanel.Update();
                    delAgrupadoModalpopupextender.Show();

                }
                if (((Button)sender).ID == eliminarReAgrupadoButton.ID)
                {

                    //ECItemElimReAgrupadoPanel1.ListView.DataSource =
                    //    new EstructuraCostoBL().GetAgrupadoList(2, int.Parse(internalid.Value));
                    ECItemElimReAgrupadoPanel1.DataBind();
                    delReAgrupadoUpdatePanel.Update();
                    ReEliAgruparRecursoModalPPE.Show();

                }
                


            }



            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        protected void accionAgrupado_Click(object sender, EventArgs e)
        {
            try
            {
               
                    List<EstructuraCostoItemRecursoInfo> ECItemList =
                        (List<EstructuraCostoItemRecursoInfo>)Session[idRecursoList.Value];
                    List<EstructuraCostoitemsingleInfo> 
                        recursoNuevos = (List<EstructuraCostoitemsingleInfo>)Session[idRecursoNewList.Text];
                    
                    bol.addECItemAgrupado(int.Parse(internalid.Value),
                        monedaDDL.SelectedValue.ToInt(),
                        int.Parse(idObra.Value),
                        ECItemList,
                        recursoNuevos);

                   
                    AgrupadoTransModalpopupextenderadd.Hide();
                    BindEstructuraCostoItems();
                    setEstadisticas();
                    BindDataRecursosConfigurados();
              
                


            }
            catch (SqlException sqlex)
            {
                AgrupadoTransModalpopupextenderadd.Show();
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                AgrupadoTransModalpopupextenderadd.Show();
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }


        #endregion

        protected void ecitemGridView_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((EstructuraCostoItemConfInfo)e.Row.DataItem != null)
                {
                    var a = (EstructuraCostoItemConfInfo)e.Row.DataItem;

                    if (a.cantidadUso > a.cantidad)
                    {
                        //compras de  mas 
                        e.Row.BackColor = Color.FromName("#CCFFFF");
                    }
                    if (a.total >= a.totalUso)
                    {
                        //verde
                        e.Row.Cells[9].ForeColor = Color.FromName("#009900");

                    }
                    else
                    //if (a.total < a.totalUso)
                    {
                        //rojo
                        //if (a.totalUso- a.total>1)
                        e.Row.Cells[9].ForeColor = Color.FromName("#CC0000");
                        //else
                        //verde
                        //    e.Row.Cells[9].ForeColor = Color.FromName("#009900");

                    }
                    if (a.cantidad >= a.cantidadUso)
                    {
                        //verde
                        e.Row.Cells[6].ForeColor = Color.FromName("#009900");

                    }
                    else
                    //if (a.cantidad < a.cantidadUso)
                    {
                        //rojo
                        e.Row.Cells[6].ForeColor = Color.FromName("#CC0000");

                    }
                    if (a.cantidadUso < 0)
                    {
                        //naranja
                        e.Row.Cells[6].ForeColor = Color.FromName("#FF6600");

                    }


                }
            }
        }

        protected void cargaDetalle_click(object sender, EventArgs e)
        {
            try
            {
                ImageButton lnkdivrecurso = (ImageButton)sender;
                int idEC = int.Parse(lnkdivrecurso.CommandName);
                int rowindex = int.Parse(lnkdivrecurso.CommandArgument);
                string div = "div" + idEC.ToString();
                string script = String.Empty;

                Panel divcol = (Panel)recursoGridView.Rows[rowindex].FindControl("divgrillan1");

                if (lnkdivrecurso.ImageUrl == "../../Images/expand_button.png")
                {
                    GridView gv = (GridView)recursoGridView.Rows[rowindex].FindControl("GridView2");
                    UpdatePanel panel = (UpdatePanel)recursoGridView.Rows[rowindex].FindControl("UpdateDetalleECItemUpdatePanel");



                    gv.DataSource = new EstructuraCostoBL().getEstructuraCostoItemNivel1(idEC);
                    gv.DataBind();

                    lnkdivrecurso.ImageUrl = "../../Images/expand_button_down.png";
                    divcol.Style.Add("display", "inline");


                    panel.Update();
                }
                else
                {
                    lnkdivrecurso.ImageUrl = "../../Images/expand_button.png";
                    divcol.Style.Add("display", "none");
                }




            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        protected void cargaDetalleDetalle_click(object sender, EventArgs e)
        {
            try
            {
                ImageButton lnkdivrecurso = (ImageButton)sender;
                int idEC = int.Parse(lnkdivrecurso.CommandName);
                int rowindex = int.Parse(lnkdivrecurso.CommandArgument);
                string div = "div" + idEC.ToString();
                string script = String.Empty;

                GridView gv1 = (GridView)recursoGridView.Rows[rowindex].FindControl("GridView2");

                Panel divcol = (Panel)gv1.Rows[rowindex].FindControl("divgrilla");

                if (lnkdivrecurso.ImageUrl == "../../Images/expand_button.png")
                {
                    GridView gv = (GridView)recursoGridView.Rows[rowindex].FindControl("GridView3");
                    UpdatePanel panel = (UpdatePanel)recursoGridView.Rows[rowindex].FindControl("UpdateDetalleDetalleECItemUpdatePanel");

                    gv.DataSource = new EstructuraCostoBL().getEstructuraCostoItemNivel1(idEC);
                    gv.DataBind();

                    lnkdivrecurso.ImageUrl = "../../Images/expand_button_down.png";
                    divcol.Style.Add("display", "inline");

                    panel.Update();
                }
                else
                {
                    lnkdivrecurso.ImageUrl = "../../Images/expand_button.png";
                    divcol.Style.Add("display", "none");
                }




            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        protected void aceptarAddButton_Click(object sender, EventArgs e)
        {
            try
            {
                //lista seleccion
                List<EstructuraCostoItemRecursoInfo> lista = ECItemSeleccionPanel1.ItemLista;

                List<EstructuraCostoItemRecursoInfo> listaAgrupado =
                    (List<EstructuraCostoItemRecursoInfo>)Session[idRecursoList.Value.ToString()];
                listaAgrupado.AddRange(lista);
                if (listaAgrupado.Count > 0)
                {
                    monedaDDL.Enabled = false;
                }
               
                if (listaAgrupado.Count > 0)
                {
                    simbolMoneda.Value = listaAgrupado.First().moneda.simbol;
                }
                



                Session[idRecursoList.Value.ToString()] = listaAgrupado;
                BindDataAgrupadoItem();

                AgrupadoTransModalpopupextenderadd.Show();
                AddRecursoECItemPopup.Hide();
               

                


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }




        protected void delRecursoAgrupado_Click(object sender, EventArgs e)
        {
            try
            {
                
                    List<int> items=ECItemElimReAgrupadoPanel2.SeleccionList;

                    foreach (var q in items)
                        {
                            EstructuraCostoBL bol = new EstructuraCostoBL();
                          bol.deleteECItemAgrupado(q);
                        }
                        delAgrupadoModalpopupextender.Hide();
                        BindEstructuraCostoItems();
                        setEstadisticas();
                        BindDataRecursosConfigurados();

               

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }

        protected void addRecursosAgrupado(object sender, EventArgs e)
        {
            try
            {
                if (((Button)sender).ID == agrupadoSelectBTN.ID)
                {

                    ECItemSeleccionPanel1.LoadRecurso(monedaDDL.SelectedValue.ToInt(),idObra.Value.ToInt(), idRecursoList.Value);
                    AddRecursoECItemPopup.Show();
                }

                if (((Button)sender).ID == reusoFinalizadosBTN.ID)
                {
                    ECItemSeleccionFinalizadoPanel1.LoadRecurso(MonedaSeleccionDDL.SelectedValue.ToInt(),
                                                               internalid.Value.ToInt(), idreUsoECItemList.Value);
                    ModalPopupExtender1.Show();

                }



            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }


        protected void addRecursosFromOC(object sender, EventArgs e)
        {
            try
            {

                if (((Button)sender).ID == REAddFromOC.ID)
                {
                    ECItemAddOCPanel1.boolEsReAgrupado = 0;
                    ECItemAddOCPanel1.LoadFromOC(internalid.Value.ToInt(), monedaDDL.SelectedValue.ToInt(), idRecursoNewList.Text);
                    ModalPopupExtenderOC.Show();
                }
                if (((Button)sender).ID == AddFromOCBTN.ID)
                {
                    ECItemAddOCPanel1.boolEsReAgrupado = 1;
                    ECItemAddOCPanel1.LoadFromOC(internalid.Value.ToInt(),
                                                    MonedaSeleccionDDL.SelectedValue.ToInt(),
                                                    idNewInsumosECItemList.Value);
                    ModalPopupExtenderOC.Show();
                }
               

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }

        #region "Grafico de Analis de Estructura"

        protected void usoInsumoComp_Click(object sender, EventArgs e)
        {
            try
            {
                //ComparativoBL bol=new ComparativoBL();

                //UsoInsumoGridView.DataSource = bol.getComparativoItemSelec(int.Parse(internalid.Value));
                //UsoInsumoGridView.DataBind();
                //    UsoInsumoUpdatePanel.Update();

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }


        protected void Load_Grafico()
        {
            //MSBar2DChart oChart = new MSBar2DChart();

            //// Set properties
            //oChart.Background.BgColor = "ffffff";
            //oChart.Background.BgAlpha = 50;
            //oChart.ChartTitles.Caption = "Insumos Utilizados en Comparativos";
            //oChart.ChartTitles.SubCaption = "Reporte en soles (S/.)";

            //// Set a template
            //oChart.Template = new Libero.FusionCharts.Template.OceanTemplate();

            //// Set data
            //// Add Categories Data.


            //var w = (from a in DbUtil.Db.ComparativoItemSelecPrv
            //         where a.ComparativoItem.EstructuraCostoItem.idEstructuraCosto == int.Parse(internalid.Value)
            //         group a by a.ComparativoItem.codigo into g
            //         select new EstructuraCostoUsoInfo
            //         {
            //             codigo = g.First().ComparativoItem.codigo,
            //             descripcion = g.First().ComparativoItem.descripcion,
            //             proveedor = String.Format("(Num:{0}) {1}", g.First().ComparativoProveedor.Comparativo.numDocumento, g.First().ComparativoProveedor.Proveedor.descripcion),
            //             total = g.Sum(p => p.total * p.ComparativoItem.tipoCambio).Value
            //         }).OrderByDescending(p => p.total);
            //if (w.Count() > 0)
            //{
            //    DataTable dt = UtilityExtensions.Util.EntidadToDataTable(w);
            //    GridView1.DataSource = dt;
            //    GridView1.DataBind();

            //    oChart.DataSource = dt;
            //    oChart.DataCategoryTextField = "codigo";
            //    oChart.DataSeriesTextField = "Proveedor";
            //    oChart.DataSeriesValueField = "total";
            //}
            ////oChart.DataBind();

            //// Link the WebControl and the Chart
            //chtProductSales.ShowChart(oChart);
        }
        #endregion

        protected void cancelardelRecursoAgrupadoButton_Click(object sender, EventArgs e)
        {

        }

       
        protected void Button3_Click(object sender, EventArgs e)
        {
            try
            {

                if (ECItemAddOCPanel1.boolEsReAgrupado==0)
                {
                    var lista = ECItemAddOCPanel1.GetSeleccionList(monedaDDL.SelectedValue.ToInt(),
                                                               tipoCambioOBRADOL.Value.ToDecimal().Value,
                                                               simbolOBRADOL.Value,
                                                               simbolMonedaBase.Value);

                    List<EstructuraCostoitemsingleInfo> itemNewRecurso =
                            (List<EstructuraCostoitemsingleInfo>)Session[idRecursoNewList.Text.ToString()];

                    itemNewRecurso.AddRange(lista);
                    Session[idRecursoNewList.Text.ToString()] = itemNewRecurso;
                    BindDataItem();
                    AgrupadoTransModalpopupextenderadd.Show();
                    AddRecursoECItemPopup.Hide();
                }
                if (ECItemAddOCPanel1.boolEsReAgrupado == 1)
                {
                    var lista = ECItemAddOCPanel1.GetSeleccionList(MonedaSeleccionDDL.SelectedValue.ToInt(),
                                                              tipoCambioOBRADOL.Value.ToDecimal().Value,
                                                              simbolOBRADOL.Value,
                                                              simbolMonedaBase.Value);//segun la moned seleccionada
                   

                    List<EstructuraCostoitemsingleInfo> itemNewRecurso =
                            (List<EstructuraCostoitemsingleInfo>)Session[idNewInsumosECItemList.Value.ToString()];

                    itemNewRecurso.AddRange(lista);
                    Session[idNewInsumosECItemList.Value.ToString()] = itemNewRecurso;
                    BindDataNewItemRen();
                    
                    AddRecursoECItemPopup.Hide();
                }
               
            }

            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        protected void monedaDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
           try
            {
               // si cambia la moneda se actualiza las ordenes de compra
                List<EstructuraCostoitemsingleInfo> itemNewRecurso =
                    (List<EstructuraCostoitemsingleInfo>)Session[idRecursoNewList.Text.ToString()];

                foreach (EstructuraCostoitemsingleInfo item in itemNewRecurso)
                {
                    item.cambiarMoneda(monedaDDL.SelectedValue.ToInt(),
                        tipoCambioOBRADOL.Value.ToDecimal().Value,
                        simbolOBRADOL.Value,simbolMonedaBase.Value);
                }

                Session[idRecursoNewList.Text.ToString()] = itemNewRecurso;
                BindDataItem();

            }
           catch (SqlException sqlex)
           {
               WebServerSideSqlError.Log(sqlex);
               ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


           }
           catch (Exception ex)
           {
               WebServerSideError.Log(ex);
               ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

           }
        }

        #region ReAgrupar



        protected void AddSeleccReUsoBtn_Click(object sender, EventArgs e)
        {
            try
            {
                //lista seleccion
                List<EstructuraCostoitemReUsoInfo> lista = ECItemSeleccionFinalizadoPanel1.ItemLista;

                List<EstructuraCostoitemReUsoInfo> listaAgrupado =
                    (List<EstructuraCostoitemReUsoInfo>)Session[idreUsoECItemList.Value.ToString()];
                listaAgrupado.AddRange(lista);

                if (listaAgrupado.Count > 0)
                {
                    MonedaSeleccionDDL.Enabled = false;
                }

                if (listaAgrupado.Count > 0)
                {
                    simbolMoneda.Value = DbUtil.Db.EstructuraCostoItems.
                        Single(p => p.idInternal == listaAgrupado.First().idInternal).Moneda.simbol;
                }


                Session[idreUsoECItemList.Value.ToString()] = listaAgrupado;
                 BindDataItemFin();

               ReAgruparRecursoModalPPE.Show();
                ModalPopupExtenderOC.Hide();





            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }



        protected void aceptarReAgrupar_Click(object sender, EventArgs e)
        {

            try
            {

                List<EstructuraCostoitemReUsoInfo> ECItemList =
                        (List<EstructuraCostoitemReUsoInfo>)Session[idreUsoECItemList.Value];
                List<EstructuraCostoitemsingleInfo>
                    recursoNuevos = (List<EstructuraCostoitemsingleInfo>)Session[idNewInsumosECItemList.Value];


               
                
                bol.addECItemReAgrupado(int.Parse(internalid.Value),
                    MonedaSeleccionDDL.SelectedValue.ToInt(),
                    int.Parse(idObra.Value),
                    ECItemList,
                    recursoNuevos);

                setEstadisticas();
                BindDataRecursosConfigurados();

                ReAgruparRecursoModalPPE.Hide();


            }
            catch (SqlException sqlex)
            {
                ReAgruparRecursoModalPPE.Show();
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                ReAgruparRecursoModalPPE.Show();
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }


        }

        protected void delRecursoReAgrupado_Click(object sender, EventArgs e)
        {
            try
            {

                List<int> lista = ECItemElimReAgrupadoPanel1.SeleccionList;

                EstructuraCostoBL bol = new EstructuraCostoBL();
                foreach (var item in lista)
                {
                    bol.deleteECItemReAgrupado(item);
                }

                setEstadisticas();
                BindDataRecursosConfigurados();
                ReEliAgruparRecursoModalPPE.Hide();





            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }


        public void LoadListaDisponible()
        {
            
            //cargar por defecto el  valor de solo los comparativos finalizados
            List<EstructuraCostoitemReUsoInfo> item = new List<EstructuraCostoitemReUsoInfo>();

            Session[idreUsoECItemList.Value.ToString()] = item;
            BindDataItemFin();
        }
        public void LoadNuevoUso()
        {
            List<EstructuraCostoitemsingleInfo> itemList = new List<EstructuraCostoitemsingleInfo>();
            Session[idNewInsumosECItemList.Value.ToString()] = itemList;
            BindDataNewItemRen();
        }
        private void setEstadistica()
        {
            List<EstructuraCostoitemsingleInfo> itema =
                (List<EstructuraCostoitemsingleInfo>)Session[idNewInsumosECItemList.Value.ToString()];

            List<EstructuraCostoitemReUsoInfo> itemb =
               (List<EstructuraCostoitemReUsoInfo>)Session[idreUsoECItemList.Value.ToString()];


            totalRecursoLBL.Text = String.Format("{0} {1:N}", simbolMonedaLabel.Value, itemb.Sum(p => p.totalReUso));
            totalNewUsoLBL.Text = String.Format("{0} {1:N}", simbolMonedaLabel.Value, itema.Sum(p => p.total));
            saldoReAgrupadoLBL.Text = String.Format("{0} {1:N}", simbolMonedaLabel.Value, itemb.Sum(p => p.totalReUso) - itema.Sum(p => p.total));
            //   
            totalesUNL.Update();
        }

        protected void MonedaSeleccionDDL_Chk(object sender, EventArgs e)
        {

            
            //cambiamos la menda de lo nuevo
            simbolMonedaLabel.Value = DbUtil.Db.Monedas.Single(p => p.idInternal == int.Parse(MonedaSeleccionDDL.SelectedValue)).simbol;
            
            
            UpdateModNewRecurso(simbolMonedaLabel.Value, MonedaSeleccionDDL.SelectedValue.ToInt());

        }

        #region "Comparativos Finalizados"

        private void BindDataItemFin()
        {

            List<EstructuraCostoitemReUsoInfo> item =
                (List<EstructuraCostoitemReUsoInfo>)Session[idreUsoECItemList.Value.ToString()];

            MonedaSeleccionDDL.Enabled = true;

            if (item.Count > 0)
            {
                MonedaSeleccionDDL.Enabled = false;
            }

            reUsoECItemGridView.DataSource = item;
            reUsoECItemGridView.DataBind();

            recursoItemUpdatePanel.Update();
            setEstadistica();

        }

        protected void DeleteItemFin(object sender, EventArgs e)
        {
            try
            {

                ImageButton lnkRemove = (ImageButton)sender;
                int idInternal = int.Parse(lnkRemove.CommandArgument.ToString());

                List<EstructuraCostoitemReUsoInfo> estructuraCostoitemReUsoInfo =
                    (List<EstructuraCostoitemReUsoInfo>)Session[idreUsoECItemList.Value.ToString()];

                EstructuraCostoitemReUsoInfo drw = estructuraCostoitemReUsoInfo.Single(p => p.idInternal == idInternal);

                //eliminamos de la coleccion

                estructuraCostoitemReUsoInfo.Remove(drw);
                Session[idreUsoECItemList.Value.ToString()] = estructuraCostoitemReUsoInfo;



                BindDataItemFin();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        protected void UpdateItemFin(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);

                string totalReUso =
                    ((TextBox)gv.Rows[e.RowIndex].FindControl("totalDispEditTxt")).Text;


                int idinternal = int.Parse(gv.DataKeys[e.RowIndex].Values[0].ToString());


                List<EstructuraCostoitemReUsoInfo> itemList =
                    (List<EstructuraCostoitemReUsoInfo>)Session[idreUsoECItemList.Value];

                EstructuraCostoitemReUsoInfo item = itemList.Single(p => p.idInternal == idinternal);

                //validados que no sea mayor
                if (item.totalDisp < decimal.Parse(totalReUso))
                {
                    string msg = String.Format("el total de  Item {0} es superior al disponible", item.descripcion);
                    throw new Exception(msg);
                }

                item.totalReUso = decimal.Parse(totalReUso);
                item.totalReUsoStr = simbolMonedaLabel.Value + " " + item.totalReUso.ToString("N");


                Session[idreUsoECItemList.Value.ToString()] = itemList;

                gv.EditIndex = -1;

                BindDataItemFin();

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void EditItemFin(object sender, GridViewEditEventArgs e)
        {
            try
            {
                reUsoECItemGridView.EditIndex = e.NewEditIndex;
                BindDataItemFin();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void CancelItemFin(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                reUsoECItemGridView.EditIndex = -1;
                BindDataItem();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }


     

        #endregion
        #region "Nuevos Recursos"

        private void resetEmptyRen()
        {
            if (nuevoUsoAgrupadoGridView.Rows.Count == 0)
            {
                List<EstructuraCostoitemsingleInfo> itemList0 = new List<EstructuraCostoitemsingleInfo>();
                EstructuraCostoitemsingleInfo itemcero = new EstructuraCostoitemsingleInfo();
                itemcero.idInternal = 0;
                itemList0.Add(itemcero);
                nuevoUsoAgrupadoGridView.DataSource = itemList0;
                nuevoUsoAgrupadoGridView.DataBind();
                nuevoUsoAgrupadoGridView.Rows[0].Visible = false;
            }

        }

        private void UpdateModNewRecurso(string simbolNew, int idMoneda)
        {

            List<EstructuraCostoitemsingleInfo> itemList =
                (List<EstructuraCostoitemsingleInfo>)Session[idNewInsumosECItemList.Value.ToString()];
            
            foreach (EstructuraCostoitemsingleInfo item in itemList)
            {
                item.cambiarMoneda(idMoneda,
                    tipoCambioOBRADOL.Value.ToDecimal().Value,
                    simbolOBRADOL.Value, simbolNew);
            }

            Session[idRecursoNewList.Text.ToString()] = itemList;

            BindDataNewItemRen();
        }
        private void BindDataNewItemRen()
        {

            List<EstructuraCostoitemsingleInfo> item =
                (List<EstructuraCostoitemsingleInfo>)Session[idNewInsumosECItemList.Value.ToString()];

            nuevoUsoAgrupadoGridView.DataSource = item;
            nuevoUsoAgrupadoGridView.DataBind();
            resetEmptyRen(); //necesario para add

            nuevoUsoAgrupadoGridView.FooterRow.Visible = true;
            recursoNewItemUpdatePanel.Update();
            setEstadistica();
        }

        protected void DeleteNewItemRen(object sender, EventArgs e)
        {
            try
            {

                ImageButton lnkRemove = (ImageButton)sender;
                int idInternal = int.Parse(lnkRemove.CommandArgument.ToString());

                List<EstructuraCostoitemsingleInfo> itemList =
                    (List<EstructuraCostoitemsingleInfo>)Session[idNewInsumosECItemList.Value.ToString()];

                EstructuraCostoitemsingleInfo drw = itemList.Single(p => p.idInternal == idInternal);

                //eliminamos de la coleccion

                itemList.Remove(drw);
                Session[idNewInsumosECItemList.Value.ToString()] = itemList;



                BindDataNewItemRen();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void UpdateNewItemRen(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);


                string idInsumo = ((TextBox)gv.Rows[e.RowIndex].FindControl("idInsumoEditTxt")).Text;
                string cantidad = ((TextBox)gv.Rows[e.RowIndex].FindControl("cantidadEditTxt")).Text;
                string precio = ((TextBox)gv.Rows[e.RowIndex].FindControl("precioEditTxt")).Text;
                // string total = ((TextBox)gv.Rows[e.RowIndex].FindControl("totalEditTxt")).Text;

                int idinternal = int.Parse(gv.DataKeys[e.RowIndex].Values[0].ToString());


                List<EstructuraCostoitemsingleInfo> itemList =
                    (List<EstructuraCostoitemsingleInfo>)Session[idNewInsumosECItemList.Value];

                EstructuraCostoitemsingleInfo item = itemList.Single(p => p.idInternal == idinternal);


                //validamos que total
                decimal total = decimal.Parse(cantidad) * decimal.Parse(precio);
                if (idInsumo == String.Empty)
                {
                    throw new Exception("ingrese Insumo");
                }

                DAL.Insumo insumo = DbUtil.Db.Insumos.Single(p => p.codigo == idInsumo);



                item.idInsumo = insumo.idInternal;
                item.codigo = insumo.codigo;
                item.descripcion = insumo.descripcion;
                item.unidad = insumo.InsumoUnidad.abreviacion;
                item.cantidad = decimal.Parse(cantidad);
                item.precio = decimal.Parse(precio);
                item.total = total;
                item.simbol = simbolMonedaLabel.Value;
                item.idMoneda = MonedaSeleccionDDL.SelectedValue.ToInt();

                Session[idNewInsumosECItemList.Value.ToString()] = itemList;

                gv.EditIndex = -1;

                BindDataNewItemRen();

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void EditNewItemRen(object sender, GridViewEditEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);

                gv.EditIndex = e.NewEditIndex;
                BindDataNewItemRen();
                gv.FooterRow.Visible = false;


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void CancelNewItemRen(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);
                gv.EditIndex = -1;
                BindDataNewItemRen();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void AddNewItemRen(object sender, EventArgs e)
        {
            try
            {

                List<EstructuraCostoitemsingleInfo> itemlist =
                  (List<EstructuraCostoitemsingleInfo>)Session[idNewInsumosECItemList.Value];


                string idInsumo = ((TextBox)nuevoUsoAgrupadoGridView.FooterRow.FindControl("idInsumoInsertTxt")).Text;
                string cantidad = ((TextBox)nuevoUsoAgrupadoGridView.FooterRow.FindControl("cantidadInsertTxt")).Text;
                string precioStr = ((TextBox)nuevoUsoAgrupadoGridView.FooterRow.FindControl("precioInsertTxt")).Text;
                string totalStr = ((TextBox)nuevoUsoAgrupadoGridView.FooterRow.FindControl("totalInsertTxt")).Text;

                decimal precio = Math.Round(decimal.Parse(totalStr) / decimal.Parse(cantidad),4);

                if (idInsumo == String.Empty)
                {
                    throw new Exception("ingrese Insumo");
                }

                DAL.Insumo insumo = DbUtil.Db.Insumos.Single(p => p.codigo == idInsumo);

                EstructuraCostoitemsingleInfo item = new EstructuraCostoitemsingleInfo(Util.GenerarID(),
                                                                                        insumo.idInternal,
                                                                                        insumo.codigo,
                                                                                        insumo.descripcion,
                                                                                        insumo.InsumoUnidad.abreviacion,
                                                                                        precio,
                                                                                        decimal.Parse(cantidad),
                                                                                        decimal.Parse(totalStr),
                                                                                        simbolMonedaLabel.Value,
                                                                                        MonedaSeleccionDDL.SelectedValue.ToInt());

                itemlist.Add(item);
                Session[idNewInsumosECItemList.Value.ToString()] = itemlist;
                BindDataNewItemRen();

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
     

        protected void AddReUsoAgrupado_Click(object sender, EventArgs e)
            {
                try
                {

                    List<EstructuraCostoitemReUsoInfo> ECItemList =
               (List<EstructuraCostoitemReUsoInfo>)Session[idreUsoECItemList.Value.ToString()];

                    List<EstructuraCostoitemsingleInfo> recursoNuevos =
                (List<EstructuraCostoitemsingleInfo>)Session[idNewInsumosECItemList.Value.ToString()];

                  
                    bol.addECItemReAgrupado(int.Parse(internalid.Value),
                        MonedaSeleccionDDL.SelectedValue.ToInt(),
                        int.Parse(idObra.Value),
                        ECItemList,
                        recursoNuevos);


                    AgrupadoTransModalpopupextenderadd.Hide();
                    BindEstructuraCostoItems();
                    setEstadisticas();
                    BindDataRecursosConfigurados();
                    ReAgruparRecursoModalPPE.Hide();
                    


                }
                catch (SqlException sqlex)
                {
                    WebServerSideSqlError.Log(sqlex);
                    ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                     "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


                }
                catch (Exception ex)
                {
                    WebServerSideError.Log(ex);
                    ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

                }
            }
        #endregion

       
        #endregion



           protected void RowDataBoundselecitem(Object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                
                //control de cambios para no editar los finalizados 
                if (
                    (((ImageButton)e.Row.Cells[8].Controls[0])).CommandName == "Edit" &
                    (((EstructuraCostoItemRecursoInfo)(e.Row.DataItem)).idInsumo!= 12954))
                   
                {                                                                           
                    (((ImageButton)e.Row.Cells[8].Controls[0])).Visible = false;
                }
            }
        }


           protected void UpdateselecItem(object sender, GridViewUpdateEventArgs e)
           {
               try
               {
                   GridView gv = ((GridView)sender);
                   TextBox totalTXT =
                       ((TextBox)gv.Rows[e.RowIndex].FindControl("totalTXT"));
                  


                   int idinternal = int.Parse(gv.DataKeys[e.RowIndex].Values[0].ToString());




                   List<EstructuraCostoItemRecursoInfo> itemList =
                       (List<EstructuraCostoItemRecursoInfo>)Session[idRecursoList.Value.ToString()];

                   EstructuraCostoItemRecursoInfo drw = itemList.Single(p => p.idInternal == idinternal);

                   //eliminamos de la coleccion
                   drw.total = totalTXT.Text.ToDecimal().Value;
                   drw.precio = totalTXT.Text.ToDecimal().Value;
                   drw.precioStr =string.Format("{0}{1:N}",drw.moneda.simbol,totalTXT.Text);
                   drw.totalStr = string.Format("{0}{1:N}", drw.moneda.simbol, totalTXT.Text);

                   Session[idRecursoList.Value.ToString()] = itemList;


                   gv.EditIndex = -1;
                   BindDataAgrupadoItem();

               }
               catch (SqlException sqlex)
               {
                   WebServerSideSqlError.Log(sqlex);
                   ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                    "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


               }
               catch (Exception ex)
               {
                   WebServerSideError.Log(ex);
                   ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                    "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

               }

           }
           protected void EditselecItem(object sender, GridViewEditEventArgs e)
           {
               try
               {
                   GridView gv = ((GridView)sender);
                   gv.EditIndex = e.NewEditIndex;
                   BindDataAgrupadoItem();
               }
               catch (SqlException sqlex)
               {
                   WebServerSideSqlError.Log(sqlex);
                   ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                    "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


               }
               catch (Exception ex)
               {
                   WebServerSideError.Log(ex);
                   ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                    "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

               }

           }
           protected void CancelselecItem(object sender, GridViewCancelEditEventArgs e)
           {
               try
               {
                   GridView gv = ((GridView)sender);
                  
                   gv.EditIndex = -1;
                   BindDataAgrupadoItem();


               }
               catch (SqlException sqlex)
               {
                   WebServerSideSqlError.Log(sqlex);
                   ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                    "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


               }
               catch (Exception ex)
               {
                   WebServerSideError.Log(ex);
                   ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                    "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

               }

           }
    }
}


